<?php
/**
 * communit.as
 * @copyright (C)2008 Jaybill McCarthy, All Rights Reserved.
 * @category communitas
 * @package communitas
 * @author Jaybill McCarthy
 * @link http://communit.as communit.as
 * @license http://communit.as/docs/license License
 */

/**
 *
 * @package communitas
 * @subpackage forum_controllers
 * @license http://communit.as/docs/license License 
 */

class Forum_SubjectController extends Forum_Controller_Action_Abstract {
	var $_last_login_on = null;

	function init(){	
		$this->view->pagetitle = "subjects";
		
		parent::init();		
	}

	function editAction(){
		$request = new Cts_Request($this->getRequest());
		$subjects_table = new Subjects();		
		if(!$request->has('id')){					
			$this->view->pagetitle = "New Subject";
		} else {
			$this->view->pagetitle = "Edit Subject";
			$where = $subjects_table->getAdapter()->quoteInto('id = ?',$request->id);
			$subject = $subjects_table->fetchRow($where);
			if(!is_null($subject)){
				$this->view->id = $subject->id;
				$this->view->title = $subject->title;
				$this->view->description = $subject->description;
				$this->view->active = $subject->active;
				$this->view->mode = "edit"; 
			}
		}
		
		if($this->_request->isPost()){				
			$errors = array();
			
			if(!Cts_Validate::checkLength($request->id,1,16)){
				$errors[] = $this->_T("subject ID must be between 1 and 16 chars");
			}
			
			if(!Cts_Validate::checkLength($request->title,1,256)){
				$errors[] = $this->_T("subject Title must be between 1 and 256 chars");
			}

			if($subjects_table->getCountByWhereClause($where) > 0 and $request->mode != "edit"){
				$errors[] = $this->_T("The subject ID %s is already in use", $request->id);
			}
			
			if(count($errors) > 0){
				$this->view->errors = $errors;
				$this->view->id = $request->id;
				$this->view->title = $request->title;
				$this->view->description = $request->description;
				$this->view->active = $request->active;
			} else {
				$data = array(
					'title' => $request->title,
					'description' => $request->description,
					'active' => (int)$request->active,					
				);
				
				
				if($request->mode == "edit"){
					$subjects_table->update($data,$where);					
				} else {						
					$data['id'] = $request->id;
					$subjects_table->insert($data);
				}
				
				$this->_redirect('/forum');
			}
			
		}
		
		
	}
	
}